// import { fileURLToPath, URL } from 'node:url'
import { defineConfig, loadEnv } from 'vite'
import { convertEnv, getSrcPath, getRootPath } from './build/utils'
import { createVitePlugins } from './build/plugin'

export default defineConfig(({ command, mode }) => {
  const srcPath = getSrcPath()
  const rootPath = getRootPath()
  const isBuild = command === 'build'
  const envDir = './env'

  const env = loadEnv(mode, envDir)
  const viteEnv = convertEnv(env)
  const { VITE_PORT, VITE_PUBLIC_PATH, VITE_BASE_API } = viteEnv

  return {
    base: VITE_PUBLIC_PATH || '/',
    envDir: envDir,
    resolve: {
      alias: {
        '~': rootPath,
        '@': srcPath
      },
      extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue']
    },
    define: {
      // enable hydration mismatch details in production build
      __VUE_PROD_HYDRATION_MISMATCH_DETAILS__: true
    },
    plugins: createVitePlugins(viteEnv, isBuild),
    server: {
      host: true,
      port: VITE_PORT,
      open: true,
      proxy: {
        [VITE_BASE_API]: {
          target: 'http://127.0.0.1:8080',
          changeOrigin: true,
          rewrite: (path) => path.replace(new RegExp(`^${VITE_BASE_API}`), '/')
        }
      }
    },
    build: {
      emptyOutDir: true,
      // 是否启用文件计算
      reportCompressedSize: false,
      // 是否生成map文件
      sourcemap: false,
      /** 分包大小 */
      chunkSizeWarningLimit: 1024,
      minify: 'terser',
      /** 在打包代码时移除 console.log、debugger 和 注释 */
      terserOptions: {
        compress: {
          drop_console: true, // 删除所有调式带有console的
          drop_debugger: true
          // pure_funcs: ["console.log"] // 删除console.log
        },
        format: {
          /** 删除注释 */
          comments: false
        }
      },
      /** 打包后静态资源目录 */
      assetsDir: 'static',
      rollupOptions: {
        output: {
          assetFileNames: 'static/[ext]/[name]-[hash].[ext]',
          chunkFileNames: 'static/js/[name]-[hash].js',
          entryFileNames: 'static/js/[name]-[hash].js'
        }
      }
    }
  }
})
